<template>
  <div class="flex items-center w-full pr-4 bg-white border-b-2 border-gray-200 border-b-solid">
    <el-tabs
      v-model="activeTab"
      type="card"
      class="custom-tabs flex-1"
      @tab-change="switchTab"
      @tab-remove="removeTab"
    >
      <el-tab-pane
        v-for="(tab, index) in tabStore.tabs"
        :key="tab.index"
        :label="tab.name"
        :name="tab.index"
        :closable="index !== 0"
      >
        <template #label>
          <span class="tab-label border-none pl-2 pr-2 bg-transparent" :ref="el => { if (el) tabRefs[tab.index] = el }">
            {{ tab.name }}
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>      
    <el-dropdown class="ml-2">
      <span class="el-dropdown-link cursor-pointer flex items-center">
        页签操作
        <el-icon class="ml-1">
          <CaretBottom/>
        </el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="refreshCurrent">刷新当前页面</el-dropdown-item>
          <el-dropdown-item @click="closeOther">除之外关闭其他</el-dropdown-item>
          <el-dropdown-item @click="closeAll">关闭所有</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { computed, defineEmits, ref, nextTick, onMounted, watch } from 'vue';
import { useTabStore } from '~/stores/tabStore';
import { useRouter } from 'vue-router';
import { CaretBottom } from '@element-plus/icons-vue';

// 类型定义
interface Tab {
  index: string;
  name: string;
}

// Store 和路由初始化
const tabStore = useTabStore();
const router = useRouter();
const tabRefs = ref<Record<string, HTMLElement>>({});

// 事件定义
const emit = defineEmits<{
  (e: 'customEvent', value: string): void;
}>();

// 计算属性
const activeTab = computed({
  get: () => tabStore.activeTab,
  set: (value: string) => tabStore.switchTab(value),
});

// 切换标签页
const switchTab = async (tabName: string) => {
  try {
    tabStore.switchTab(tabName);
    activeTab.value = tabName;
    await router.push({ path: tabName });
    emit('customEvent', activeTab.value);
    await nextTick();
    scrollToActiveTab(tabName);
  } catch (err) {
    console.error('标签页切换失败:', err);
  }
};

// 关闭标签页
const removeTab = async (tabName: string) => {
  try {
    tabStore.tabs = tabStore.tabs.filter(tab => tab.index !== tabName);

    if (tabStore.activeTab === tabName) {
      const newActiveTab = tabStore.tabs.length > 0 
        ? tabStore.tabs[tabStore.tabs.length - 1].index 
        : '/';
      
      tabStore.activeTab = newActiveTab;
      await router.push({ path: newActiveTab });
      await nextTick();
      scrollToActiveTab(newActiveTab);
    }

    activeTab.value = tabStore.activeTab;
    emit('customEvent', activeTab.value);
  } catch (err) {
    console.error('标签页关闭失败:', err);
  }
};

// 滚动到活动标签
const scrollToActiveTab = (tabName: string) => {
  const tabElement = tabRefs.value[tabName];
  if (tabElement) {
    const navScroll = tabElement.closest('.el-tabs__nav-scroll');
    if (navScroll) {
      const tabOffset = tabElement.offsetLeft;
      const navScrollWidth = navScroll.offsetWidth;
      const tabWidth = tabElement.offsetWidth;
      
      // 计算滚动位置，使标签页居中显示
      const scrollLeft = tabOffset - (navScrollWidth / 2) + (tabWidth / 2);
      navScroll.scrollTo({
        left: Math.max(0, scrollLeft),
        behavior: 'smooth'
      });
    }
  }
};

// 监听标签变化
watch(() => tabStore.tabs.length, () => {
  nextTick(() => {
    if (activeTab.value) {
      scrollToActiveTab(activeTab.value);
    }
  });
});
// 刷新当前页面
const refreshCurrent = () => {
  window.location.reload();
}
// 关闭其他
const closeOther = () => {
  tabStore.closeOther();
}
// 关闭所有
const closeAll = () => {
  tabStore.closeAll(router);
}
onMounted(() => {
  if (activeTab.value) {
    nextTick(() => {
      scrollToActiveTab(activeTab.value);
    });
  }
});
</script>

<style lang="postcss" scoped>
.custom-tabs {
  min-width: 0; /* 防止tabs溢出 */
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.el-dropdown-link {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

:deep(.el-tabs__nav-wrap) {
  padding-right: 0;
}

/* 自定义标签页样式 */
:deep(.custom-tabs) {
  @apply pr-2;
  height: 40px; /* 确保固定高度 */
}

:deep(.ep-tabs__header),
:deep(.el-tabs__header) {
  margin: 0 !important;
  padding: 0;
  border: none;
  height: 100%;
}

:deep(.el-tabs__nav-scroll) {
  @apply overflow-x-auto overflow-y-hidden;
  margin: 0;
  padding: 0;
  height: 100%;
  scrollbar-width: none;
  -ms-overflow-style: none;
  &::-webkit-scrollbar {
    display: none;
  }
}

:deep(.el-tabs__nav) {
  @apply border-none;
  margin: 0;
  padding: 0;
  white-space: nowrap;
  position: relative;
  transition: transform 0.3s;
  height: 100%;
}

:deep(.el-tabs__item) {
  @apply transition-all duration-200;
  margin: 0 !important;
  padding: 0 16px;
  border: none;
  height: 100%;
  line-height: 40px;
  
  &:hover {
    @apply text-blue-600;
  }
  
  &.is-active {
    @apply bg-blue-50 text-blue-600;
  }
}

.tab-label {
  @apply inline-flex items-center whitespace-nowrap;
  margin: 0;
  padding: 0;
  
  .el-icon {
    @apply ml-1 text-gray-400;
    
    &:hover {
      @apply text-blue-600;
    }
  }
}
</style>